|
| 1 | +package httpsig |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/dunglas/httpsfv" |
| 9 | +) |
| 10 | + |
| 11 | +type signatureBase []component |
| 12 | + |
| 13 | +func newSignatureBase(params *signatureParameters, msg *Message) (signatureBase, error) { |
| 14 | + marshalledSigParams, err := httpsfv.Marshal(params.InnerList) |
| 15 | + if err != nil { |
| 16 | + return nil, err |
| 17 | + } |
| 18 | + |
| 19 | + sigBase := make(signatureBase, 0, len(params.identifiers)+1) |
| 20 | + seen := make(map[string]struct{}, len(params.identifiers)) |
| 21 | + |
| 22 | + for _, ci := range params.identifiers { |
| 23 | + identifier, err := httpsfv.Marshal(ci.Item) |
| 24 | + if err != nil { |
| 25 | + return nil, err |
| 26 | + } |
| 27 | + |
| 28 | + if _, ok := seen[identifier]; ok { |
| 29 | + return nil, fmt.Errorf("%w: duplicate component identifier %s", ErrMalformedData, identifier) |
| 30 | + } |
| 31 | + |
| 32 | + seen[identifier] = struct{}{} |
| 33 | + |
| 34 | + comp, err := ci.createComponent(msg) |
| 35 | + if err != nil { |
| 36 | + return nil, err |
| 37 | + } |
| 38 | + |
| 39 | + sigBase = append(sigBase, comp) |
| 40 | + } |
| 41 | + |
| 42 | + sigBase = append(sigBase, component{ |
| 43 | + key: &componentIdentifier{Item: httpsfv.NewItem("@signature-params")}, |
| 44 | + value: []string{marshalledSigParams}, |
| 45 | + }) |
| 46 | + |
| 47 | + return sigBase, nil |
| 48 | +} |
| 49 | + |
| 50 | +func (s signatureBase) marshal() ([]byte, error) { |
| 51 | + var buf bytes.Buffer |
| 52 | + |
| 53 | + for i, item := range s { |
| 54 | + marshalledKey, err := httpsfv.Marshal(item.key.Item) |
| 55 | + if err != nil { |
| 56 | + return nil, err |
| 57 | + } |
| 58 | + |
| 59 | + if i > 0 { |
| 60 | + buf.WriteByte('\n') |
| 61 | + } |
| 62 | + |
| 63 | + buf.WriteString(marshalledKey) |
| 64 | + buf.WriteString(": ") |
| 65 | + buf.WriteString(item.canonicalValue()) |
| 66 | + } |
| 67 | + |
| 68 | + return buf.Bytes(), nil |
| 69 | +} |
| 70 | + |
| 71 | +func (s signatureBase) components() (map[string]string, error) { |
| 72 | + result := make(map[string]string, len(s)) |
| 73 | + |
| 74 | + for _, component := range s { |
| 75 | + name := component.key.Value.(string) // nolint: forcetypeassert |
| 76 | + |
| 77 | + if name == "@signature-params" { |
| 78 | + continue |
| 79 | + } |
| 80 | + |
| 81 | + identifier, err := httpsfv.Marshal(component.key.Item) |
| 82 | + if err != nil { |
| 83 | + return nil, err |
| 84 | + } |
| 85 | + |
| 86 | + // Remove quotes around the component name, |
| 87 | + // preserving identifier parameters. |
| 88 | + prefix := `"` + name + `"` |
| 89 | + key := name + strings.TrimPrefix(identifier, prefix) |
| 90 | + |
| 91 | + result[key] = component.canonicalValue() |
| 92 | + } |
| 93 | + |
| 94 | + return result, nil |
| 95 | +} |
0 commit comments