Debian Codegraph @

pkg/oidc/util.go

raw
1 package oidc
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 )
8
9 // mergeAndMarshalClaims merges registered and the custom
10 // claims map into a single JSON object.
11 // Registered fields overwrite custom claims.
12 func mergeAndMarshalClaims(registered any, extraClaims map[string]any) ([]byte, error) {
13 // Use a buffer for memory re-use, instead of letting
14 // json allocate a new []byte for every step.
15 buf := new(bytes.Buffer)
16
17 // Marshal the registered claims into JSON
18 if err := json.NewEncoder(buf).Encode(registered); err != nil {
19 return nil, fmt.Errorf("oidc registered claims: %w", err)
20 }
21
22 if len(extraClaims) > 0 {
23 merged := make(map[string]any)
24 for k, v := range extraClaims {
25 merged[k] = v
26 }
27
28 // Merge JSON data into custom claims.
29 // The full-read action by the decoder resets the buffer
30 // to zero len, while retaining underlying cap.
31 if err := json.NewDecoder(buf).Decode(&merged); err != nil {
32 return nil, fmt.Errorf("oidc registered claims: %w", err)
33 }
34
35 // Marshal the final result.
36 if err := json.NewEncoder(buf).Encode(merged); err != nil {
37 return nil, fmt.Errorf("oidc custom claims: %w", err)
38 }
39 }
40
41 return buf.Bytes(), nil
42 }
43
44 // unmarshalJSONMulti unmarshals the same JSON data into multiple destinations.
45 // Each destination must be a pointer, as per json.Unmarshal rules.
46 // Returns on the first error and destinations may be partly filled with data.
47 func unmarshalJSONMulti(data []byte, destinations ...any) error {
48 for _, dst := range destinations {
49 if err := json.Unmarshal(data, dst); err != nil {
50 return fmt.Errorf("oidc: %w into %T", err, dst)
51 }
52 }
53 return nil
54 }