blob: 219513b861720da4d971eb3e4e6534148199ed67 [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// Copyright (C) MongoDB, Inc. 2017-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package auth
8
9import (
10 "context"
11
12 "github.com/mongodb/mongo-go-driver/x/bsonx"
13 "github.com/mongodb/mongo-go-driver/x/network/command"
14 "github.com/mongodb/mongo-go-driver/x/network/description"
15 "github.com/mongodb/mongo-go-driver/x/network/wiremessage"
16)
17
18// MongoDBX509 is the mechanism name for MongoDBX509.
19const MongoDBX509 = "MONGODB-X509"
20
21func newMongoDBX509Authenticator(cred *Cred) (Authenticator, error) {
22 return &MongoDBX509Authenticator{User: cred.Username}, nil
23}
24
25// MongoDBX509Authenticator uses X.509 certificates over TLS to authenticate a connection.
26type MongoDBX509Authenticator struct {
27 User string
28}
29
30// Auth implements the Authenticator interface.
31func (a *MongoDBX509Authenticator) Auth(ctx context.Context, desc description.Server, rw wiremessage.ReadWriter) error {
32 authRequestDoc := bsonx.Doc{
33 {"authenticate", bsonx.Int32(1)},
34 {"mechanism", bsonx.String(MongoDBX509)},
35 }
36
37 if desc.WireVersion.Max < 5 {
38 authRequestDoc = append(authRequestDoc, bsonx.Elem{"user", bsonx.String(a.User)})
39 }
40
41 authCmd := command.Read{DB: "$external", Command: authRequestDoc}
42 ssdesc := description.SelectedServer{Server: desc}
43 _, err := authCmd.RoundTrip(ctx, ssdesc, rw)
44 if err != nil {
45 return newAuthError("round trip error", err)
46 }
47
48 return nil
49}