|
| 1 | +package nanomdm |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "sync" |
| 6 | + |
| 7 | + "github.com/micromdm/nanomdm/mdm" |
| 8 | + "github.com/micromdm/nanomdm/service" |
| 9 | +) |
| 10 | + |
| 11 | +// StaticToken holds static token bytes. |
| 12 | +type StaticToken struct { |
| 13 | + token []byte |
| 14 | +} |
| 15 | + |
| 16 | +// NewStaticToken creates a new static token handler. |
| 17 | +func NewStaticToken(token []byte) *StaticToken { |
| 18 | + return &StaticToken{token: token} |
| 19 | +} |
| 20 | + |
| 21 | +// GetToken always responds with the static token bytes. |
| 22 | +func (t *StaticToken) GetToken(_ *mdm.Request, _ *mdm.GetToken) (*mdm.GetTokenResponse, error) { |
| 23 | + return &mdm.GetTokenResponse{TokenData: t.token}, nil |
| 24 | +} |
| 25 | + |
| 26 | +// TokenMux is a middleware multiplexer for GetToken check-in messages. |
| 27 | +// A TokenServiceType string is associated with a GetToken handler and |
| 28 | +// then dispatched appropriately. |
| 29 | +type TokenMux struct { |
| 30 | + typesMu sync.RWMutex |
| 31 | + types map[string]service.GetToken |
| 32 | +} |
| 33 | + |
| 34 | +// NewTokenMux creates a new TokenMux. |
| 35 | +func NewTokenMux() *TokenMux { return &TokenMux{} } |
| 36 | + |
| 37 | +// Handle registers a GetToken handler for the given service type. |
| 38 | +// See https://developer.apple.com/documentation/devicemanagement/gettokenrequest |
| 39 | +func (mux *TokenMux) Handle(serviceType string, handler service.GetToken) { |
| 40 | + if serviceType == "" { |
| 41 | + panic("tokenmux: invalid service type") |
| 42 | + } |
| 43 | + if handler == nil { |
| 44 | + panic("tokenmux: invalid handler") |
| 45 | + } |
| 46 | + mux.typesMu.Lock() |
| 47 | + defer mux.typesMu.Unlock() |
| 48 | + if mux.types == nil { |
| 49 | + mux.types = make(map[string]service.GetToken) |
| 50 | + } else if _, exists := mux.types[serviceType]; exists { |
| 51 | + panic("tokenmux: multiple registrations for " + serviceType) |
| 52 | + } |
| 53 | + mux.types[serviceType] = handler |
| 54 | +} |
| 55 | + |
| 56 | +// GetToken is the middleware that dispatches a GetToken handler based on service type. |
| 57 | +func (mux *TokenMux) GetToken(r *mdm.Request, t *mdm.GetToken) (*mdm.GetTokenResponse, error) { |
| 58 | + if t == nil { |
| 59 | + return nil, fmt.Errorf("nil MDM GetToken") |
| 60 | + } |
| 61 | + var next service.GetToken |
| 62 | + mux.typesMu.RLock() |
| 63 | + if mux.types != nil { |
| 64 | + next = mux.types[t.TokenServiceType] |
| 65 | + } |
| 66 | + mux.typesMu.RUnlock() |
| 67 | + if next == nil { |
| 68 | + return nil, fmt.Errorf("no handler for TokenServiceType: %v", t.TokenServiceType) |
| 69 | + } |
| 70 | + return next.GetToken(r, t) |
| 71 | +} |
0 commit comments