All files / src/cmap/auth auth_provider.ts

100% Statements 14/14
100% Branches 2/2
100% Functions 3/3
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  452x                 452x           5108381x                           5108381x 5108381x 5108381x               452x                     195x                             6x 4x   2x 2x 2x   2x        
import type { Document } from '../../bson';
import { MongoRuntimeError } from '../../error';
import type { HandshakeDocument } from '../connect';
import type { Connection, ConnectionOptions } from '../connection';
import type { MongoCredentials } from './mongo_credentials';
 
/**
 * Context used during authentication
 * @internal
 */
export class AuthContext {
  /** The connection to authenticate */
  connection: Connection;
  /** The credentials to use for authentication */
  credentials?: MongoCredentials;
  /** If the context is for reauthentication. */
  reauthenticating = false;
  /** The options passed to the `connect` method */
  options: ConnectionOptions;
 
  /** A response from an initial auth attempt, only some mechanisms use this (e.g, SCRAM) */
  response?: Document;
  /** A random nonce generated for use in an authentication conversation */
  nonce?: Buffer;
 
  constructor(
    connection: Connection,
    credentials: MongoCredentials | undefined,
    options: ConnectionOptions
  ) {
    this.connection = connection;
    this.credentials = credentials;
    this.options = options;
  }
}
 
/**
 * Provider used during authentication.
 * @internal
 */
export abstract class AuthProvider {
  /**
   * Prepare the handshake document before the initial handshake.
   *
   * @param handshakeDoc - The document used for the initial handshake on a connection
   * @param authContext - Context for authentication flow
   */
  async prepare(
    handshakeDoc: HandshakeDocument,
    _authContext: AuthContext
  ): Promise<HandshakeDocument> {
    return handshakeDoc;
  }
 
  /**
   * Authenticate
   *
   * @param context - A shared context for authentication flow
   */
  abstract auth(context: AuthContext): Promise<void>;
 
  /**
   * Reauthenticate.
   * @param context - The shared auth context.
   */
  async reauth(context: AuthContext): Promise<void> {
    if (context.reauthenticating) {
      throw new MongoRuntimeError('Reauthentication already in progress.');
    }
    try {
      context.reauthenticating = true;
      await this.auth(context);
    } finally {
      context.reauthenticating = false;
    }
  }
}