summaryrefslogtreecommitdiffstats
path: root/third_party/js/PKI.js/src/CertificateSet.ts
blob: 386b01ea1995ece7d85a33f7aeede4002e07b1f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import * as asn1js from "asn1js";
import * as pvutils from "pvutils";
import { Certificate, CertificateJson } from "./Certificate";
import { AttributeCertificateV1, AttributeCertificateV1Json } from "./AttributeCertificateV1";
import { AttributeCertificateV2, AttributeCertificateV2Json } from "./AttributeCertificateV2";
import { OtherCertificateFormat, OtherCertificateFormatJson } from "./OtherCertificateFormat";
import * as Schema from "./Schema";
import { PkiObject, PkiObjectParameters } from "./PkiObject";
import { AsnError } from "./errors";
import { EMPTY_STRING } from "./constants";

const CERTIFICATES = "certificates";
const CLEAR_PROPS = [
  CERTIFICATES,
];

export interface ICertificateSet {
  certificates: CertificateSetItem[];
}

export interface CertificateSetJson {
  certificates: CertificateSetItemJson[];
}

export type CertificateSetItemJson = CertificateJson | AttributeCertificateV1Json | AttributeCertificateV2Json | OtherCertificateFormatJson;

export type CertificateSetItem = Certificate | AttributeCertificateV1 | AttributeCertificateV2 | OtherCertificateFormat;

export type CertificateSetParameters = PkiObjectParameters & Partial<ICertificateSet>;

/**
 * Represents the CertificateSet structure described in [RFC5652](https://datatracker.ietf.org/doc/html/rfc5652)
 */
export class CertificateSet extends PkiObject implements ICertificateSet {

  public static override CLASS_NAME = "CertificateSet";

  public certificates!: CertificateSetItem[];

  /**
   * Initializes a new instance of the {@link CertificateSet} class
   * @param parameters Initialization parameters
   */
  constructor(parameters: CertificateSetParameters = {}) {
    super();

    this.certificates = pvutils.getParametersValue(parameters, CERTIFICATES, CertificateSet.defaultValues(CERTIFICATES));

    if (parameters.schema) {
      this.fromSchema(parameters.schema);
    }
  }

  /**
   * Returns default values for all class members
   * @param memberName String name for a class member
   * @returns Default value
   */
  public static override defaultValues(memberName: typeof CERTIFICATES): CertificateSetItem[];
  public static override defaultValues(memberName: string): any {
    switch (memberName) {
      case CERTIFICATES:
        return [];
      default:
        return super.defaultValues(memberName);
    }
  }

  /**
   * @inheritdoc
   * @asn ASN.1 schema
   * ```asn
   * CertificateSet ::= SET OF CertificateChoices
   *
   * CertificateChoices ::= CHOICE {
   *    certificate Certificate,
   *    extendedCertificate [0] IMPLICIT ExtendedCertificate,  -- Obsolete
   *    v1AttrCert [1] IMPLICIT AttributeCertificateV1,        -- Obsolete
   *    v2AttrCert [2] IMPLICIT AttributeCertificateV2,
   *    other [3] IMPLICIT OtherCertificateFormat }
   *```
   */
  public static override schema(parameters: Schema.SchemaParameters<{
    certificates?: string;
  }> = {}): Schema.SchemaType {
    const names = pvutils.getParametersValue<NonNullable<typeof parameters.names>>(parameters, "names", {});

    return (
      new asn1js.Set({
        name: (names.blockName || EMPTY_STRING),
        value: [
          new asn1js.Repeated({
            name: (names.certificates || CERTIFICATES),
            value: new asn1js.Choice({
              value: [
                Certificate.schema(),
                new asn1js.Constructed({
                  idBlock: {
                    tagClass: 3, // CONTEXT-SPECIFIC
                    tagNumber: 0 // [0]
                  },
                  value: [
                    new asn1js.Any()
                  ]
                }), // JUST A STUB
                new asn1js.Constructed({
                  idBlock: {
                    tagClass: 3, // CONTEXT-SPECIFIC
                    tagNumber: 1 // [1]
                  },
                  value: [
                    new asn1js.Sequence
                  ]
                }),
                new asn1js.Constructed({
                  idBlock: {
                    tagClass: 3, // CONTEXT-SPECIFIC
                    tagNumber: 2 // [2]
                  },
                  value: AttributeCertificateV2.schema().valueBlock.value
                }),
                new asn1js.Constructed({
                  idBlock: {
                    tagClass: 3, // CONTEXT-SPECIFIC
                    tagNumber: 3 // [3]
                  },
                  value: OtherCertificateFormat.schema().valueBlock.value
                })
              ]
            })
          })
        ]
      })
    );
  }

  public fromSchema(schema: Schema.SchemaType): void {
    // Clear input data first
    pvutils.clearProps(schema, CLEAR_PROPS);

    // Check the schema is valid
    const asn1 = asn1js.compareSchema(schema,
      schema,
      CertificateSet.schema()
    );
    AsnError.assertSchema(asn1, this.className);

    //#region Get internal properties from parsed schema
    this.certificates = Array.from(asn1.result.certificates || [], (element: any) => {
      const initialTagNumber = element.idBlock.tagNumber;

      if (element.idBlock.tagClass === 1)
        return new Certificate({ schema: element });

      //#region Making "Sequence" from "Constructed" value
      const elementSequence = new asn1js.Sequence({
        value: element.valueBlock.value
      });
      //#endregion

      switch (initialTagNumber) {
        case 1:
          // WARN: It's possible that CMS contains AttributeCertificateV2 instead of AttributeCertificateV1
          // Check the certificate version
          if ((elementSequence.valueBlock.value[0] as any).valueBlock.value[0].valueBlock.valueDec === 1) {
            return new AttributeCertificateV2({ schema: elementSequence });
          } else {
            return new AttributeCertificateV1({ schema: elementSequence });
          }
        case 2:
          return new AttributeCertificateV2({ schema: elementSequence });
        case 3:
          return new OtherCertificateFormat({ schema: elementSequence });
        case 0:
        default:
      }

      return element;
    });
    //#endregion
  }

  public toSchema(): asn1js.Set {
    // Construct and return new ASN.1 schema for this object
    return (new asn1js.Set({
      value: Array.from(this.certificates, element => {
        switch (true) {
          case (element instanceof Certificate):
            return element.toSchema();
          case (element instanceof AttributeCertificateV1):
            return new asn1js.Constructed({
              idBlock: {
                tagClass: 3,
                tagNumber: 1 // [1]
              },
              value: element.toSchema().valueBlock.value
            });
          case (element instanceof AttributeCertificateV2):
            return new asn1js.Constructed({
              idBlock: {
                tagClass: 3,
                tagNumber: 2 // [2]
              },
              value: element.toSchema().valueBlock.value
            });
          case (element instanceof OtherCertificateFormat):
            return new asn1js.Constructed({
              idBlock: {
                tagClass: 3,
                tagNumber: 3 // [3]
              },
              value: element.toSchema().valueBlock.value
            });
          default:
        }

        return element.toSchema();
      })
    }));
  }

  public toJSON(): CertificateSetJson {
    return {
      certificates: Array.from(this.certificates, o => o.toJSON())
    };
  }

}