This section provides comprehensive information about the security measures implemented within search API.
CONFIG = { . . . # ******************************************************************************* # Security Configuration # ******************************************************************************* 'security': { 'authentication': ..., 'encryption': ..., 'roles': ..., } . . . }
SearchAPI leverages the power of JSON Web Tokens (JWT) to secure all communication between clients and the API. JWT is an open standard for securely transmitting information between parties as a JSON object. It consists of a header, a payload, and a signature, which are digitally signed and encoded to form a compact and self-contained token.
The use of JWT provides several advantages in terms of security for our API. It ensures the integrity of data by digitally signing each token, making it tamper-evident. Additionally, JWT allows for stateless authentication, meaning the server does not need to store any session information. This improves scalability and reduces the
We highly recommend that you familiarize yourself with the security guidelines presented here to ensure the proper implementation and usage of SearchAPI. By following these guidelines, you can maximize the security of your API interactions and protect the confidentiality and integrity of your data.
Property | Description | Default | Type | Required |
---|---|---|---|---|
enabled | Indicates whether authentication needs to be implemented or not | false | boolean | No |
type | Indicates the type of authentication to implement | local | string | No |
secret | The secret used to sign and decrypt the JWT. Does not apply with Delegated | 52ecfd60e01b800355a8ce59780f9243b4662c3a236394ee | string/object | No |
anonymous | Indicates the body of the Anonymous user in case of no authentication | {"id": "Anonymous", "account": "[email protected]", "name": "Anonymous", "displayName": "Anonymous"} | object | No |
local | Local Authentication | Local | No | |
ldap | LDAP Authentication | LDAP | No | |
saml | SAML Authentication | SAML | No | |
oidc | OIDC Authentication | OIDC | No | |
delegated | JWKS Authentication | Delegated | No |
CONFIG = { . . . # ******************************************************************************* # Security Configuration # ******************************************************************************* 'security': { 'authentication': { "enabled": True, "type": "local", "secret": "52ecfd60e01b800355a8ce59780f9243b4662c3a236394ee", "anonymous": { "id": "Anonymous", "account": "[email protected]", "name": "Anonymous", "displayName": "Anonymous" }, "local": ..., "ldap": ..., "saml": ..., "oidc": ..., "delegated": ... } } . . . }
Almost every method available in SearchAPI has a property called attributesMapping, this property is used to remap any value in the user data provided by the authentication service into the User data available throughout the server. This transformation is achieved by mapping each key:value pair, where the value is looked up as a key in the user data from the service and remapped with the key in the User data for the server. The original key is kept, as well as any other unspecified values.
The only required values for the attributesMapping are:
Property | Description | Default | Type | Required |
---|---|---|---|---|
name | The name of the cookie used for SAML session management. | string | No | |
domain | The domain of the cookie used for SAML session management. | string | No | |
path | The path of the cookie used for SAML session management. | / | string | No |
secure | Whether the cookie used for SAML session management should only be sent over HTTPS. | false | boolean | No |
httpOnly | Whether the cookie used for SAML session management should be accessible only through the HTTP protocol. | true | boolean | No |
sameSite | Specifies the SameSite attribute value of the cookie used for SAML session management. | None | string | No |
Methods
This authentication method uses a CSV file, which involves storing user credentials in a structured format for authentication purposes. In this case, we have a CSV file with the following headers: id, account, password, email, roles, and disabled.
It's important to note that using a CSV file for authentication has limitations and may not be suitable for production systems with large user bases. However, it can serve as a simple example or proof of concept. In practice, more robust and secure methods, such as using databases, user directories, or authentication services, are typically employed for user authentication.
Property | Description | Default | Type | Required |
---|---|---|---|---|
file | CSV file with the definition of the user to have access to the server | string | Yes |
'local': { "file": "/path/to/user.csv" }
id,account,password,email,roles,disabled 1,user1,pass123,[email protected],"role1, role2",false 2,user2,pass456,[email protected],"role2, role3",true
There is a CSV file in SearchAPI located in config/auth/users.csv
LDAP (Lightweight Directory Access Protocol) is a widely adopted protocol for accessing and managing directory information services. It is a lightweight, platform-independent, and network-oriented protocol designed for directory services such as user authentication, authorization, and directory information retrieval.
LDAP is based on a client-server model, where a client application interacts with an LDAP server to perform various directory operations. The LDAP server acts as a centralized repository that stores and manages directory entries, which typically represent users, groups, devices, or other resources within an organization.
Configuration
Property | Description | Default | Type | Required |
---|---|---|---|---|
url | The LDAP server URL. It specifies the network address and protocol (e.g., ldap:// or ldaps://) for connecting to the LDAP server. | string | Yes | |
authentication | The LDAP authentication method. | SIMPLE | string | Yes |
bindDN | Contains the Distinguished Name (DN) used for binding or authenticating with the LDAP server. | string | Yes | |
bindCredentials | Contains the password or credentials associated with the bindDN. | string | Yes | |
searchBase | Specifies the base DN from which LDAP searches should begin. | string | Yes | |
searchFilter | Represents the LDAP search filter used to narrow down the search results based on specific criteria. | string | Yes | |
searchAttributes | Specifies the attributes to be returned in the search results. | array | No | |
tlsOptions | Contains TLS (Transport Layer Security) options for establishing a secure connection with the LDAP server. | object | No | |
bindProperty | Specifies the LDAP attribute used for binding or authenticating with the LDAP server. | string | No | |
groupDnProperty | Represents the LDAP attribute used to identify the distinguished name (DN) of a group. | string | No | |
groupSearchBase | Specifies the base DN from which group searches should begin. | string | No | |
groupSearchFilter | Represents the LDAP search filter used to narrow down the search results for groups based on specific criteria. | string | No | |
attributesMapping | Attribute Mapping, remaps any value in the user data provided by the authentication service, into the User data available throughout the server. | AttributesMapping | Yes |
'ldap': { "url": "ldap://ldap.example.com", "authentication": "SIMPLE", "bindDN": "cn=admin,dc=example,dc=com", "bindCredentials": "password123", "searchBase": "ou=users,dc=example,dc=com", "searchFilter": "(objectClass=person)", "searchAttributes": ["cn", "email"], "tlsOptions": { "certificateVerification": true, "cipherSuites": ["TLS_RSA_WITH_AES_256_CBC_SHA256"], "clientCertificate": "/path/to/client_certificate.pem", "clientKey": "/path/to/client_key.pem" }, "bindProperty": "uid", "groupDnProperty": "memberOf", "groupSearchBase": "ou=groups,dc=example,dc=com", "groupSearchFilter": "(objectClass=group)", "attributesMapping": { "id": "uid", "account": "sAMAccountName", "roles": ["role1", "role2"] } }
SAML2 (Security Assertion Markup Language 2.0) authentication is a standard protocol used for exchanging authentication and authorization data between a Service Provider (SP) and an Identity Provider (IdP). It enables secure single sign-on (SSO) functionality, allowing users to authenticate once with the IdP and access multiple services provided by different SPs without the need to re-enter credentials.
Configuration
Property | Description | Default | Type | Required |
---|---|---|---|---|
strict | If strict is True, then the Python Toolkit will reject unsigned or unencrypted messages if it expects them to be signed or encrypted. Also, it will reject the messages if the SAML standard is not strictly followed. Destination, NameId, Conditions, etc. are validated too. | false | boolean | No |
debug | Controls the debugging mode. When set to True, additional debug information will be logged during SAML processing. | false | boolean | No |
entity_id | Globally unique identifier for the entity and is typically a URL that represents the identity provider or service provider. | string | Yes | |
single_sign_on_service_url | The single SignOn Service URL for SAML2. | string | Yes | |
single_sign_on_service_binding | The single SignOn Service Binding for SAML2. | urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect | string | No |
single_logout_service_url | The single Logout Service URL for SAML2. | string | Yes | |
single_logout_service_binding | The single Logout Service Binding for SAML2. | urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect | string | No |
callback_url | The callback URL for SAML authentication. | http://localhost:8085/es/auth/saml/callback | string | No |
x509cert_path | Path to the public X.509 certificate of the Service Provider, used for signing requests or encrypting assertions. It should be provided in PEM format. | string | No | |
x509cert | The raw public X.509 certificate of the Service Provider, used for signing requests or encrypting assertions. | string | No | |
cert_fingerprint | Instead of using the whole X.509 cert, you can use a fingerprint in order to validate a SAMLResponse (but you still need the X.509 cert to validate LogoutRequest and LogoutResponse using the HTTP-Redirect binding). | string | No | |
cert_fingerprint_algorithm | Algorithm to use in the cert_fingerprint. | sha1 | string | No |
security | SAMLAuthSecurityConfig (Declared below) | SAMLAuthSecurityConfig | No | |
cookie | Cookie configuration to store the JWT with the current session. | CookieConfig | No | |
attributesMapping | Attribute Mapping, remaps any value in the user data provided by the authentication service into the User data available throughout the server | AttributesMapping | No |
Property | Description | Default | Type | Required |
---|---|---|---|---|
nameIdEncrypted | Indicates that the nameID of the <samlp:logoutRequest> sent by this SP will be encrypted. | false | boolean | No |
authnRequestsSigned | Indicates whether the <samlp:AuthnRequest> messages sent by this SP will be signed. [Metadata of the SP will offer this info] | false | boolean | No |
logoutRequestSigned | Indicates whether the <samlp:logoutRequest> messages sent by this SP will be signed. | false | boolean | No |
logoutResponseSigned | Indicates whether the <samlp:logoutResponse> messages sent by this SP will be signed. | false | boolean | No |
signMetadata | Sign the Metadata | false | boolean or object | No |
wantMessagesSigned | Indicates a requirement for the <samlp:Response> , <samlp:LogoutRequest> , and <samlp:LogoutResponse> elements received by this SP to be signed. | false | boolean | No |
wantAssertionsSigned | Indicates a requirement for the <saml:Assertion> elements received by this SP to be signed. [Metadata of the SP will offer this info] | false | boolean | No |
wantAssertionsEncrypted | Indicates a requirement for the <saml:Assertion> elements received by this SP to be encrypted. | false | boolean | No |
wantNameId | Indicates a requirement for the NameID element on the SAMLResponse received by this SP to be present. | true | boolean | No |
wantNameIdEncrypted | Indicates a requirement for the NameID received by this SP to be encrypted. | false | boolean | No |
wantAttributeStatement | Indicates a requirement for the AttributeStatement element. | true | boolean | No |
requestedAuthnContext | Set to false and no AuthContext will be sent in the AuthNRequest, Set true or don't present this parameter and you will get an AuthContext 'exact' 'urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport'. Set an array with the possible auth context values: array ('urn:oasis:names:tc:SAML:2.0:ac:classes:Password', 'urn:oasis:names:tc:SAML:2.0:ac:classes:X509') | true | boolean | No |
requestedAuthnContextComparison | Allows the authn comparison parameter to be set, defaults to 'exact' if the setting is not present. | exact | string | No |
failOnAuthnContextMismatch | Set to true to check that the AuthnContext(s) received match(es) the requested. | false | boolean | No |
metadataValidUntil | Provide the desired TimeStamp, for example 2015-06-26T20:00:00Z | string | No | |
metadataCacheDuration | Provide the desired Duration, for example PT518400S (6 days) | string | No | |
allowSingleLabelDomains | If enabled, URLs with single-label-domains will be allowed and not rejected by the settings validator (Enable it under Docker/Kubernetes/testing env, not recommended on production) | false | boolean | No |
signatureAlgorithm | Algorithm that the toolkit will use on the signing process. | http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 | string | No |
digestAlgorithm | Algorithm that the toolkit will use on the digest process. | http://www.w3.org/2001/04/xmlenc | No |
'saml': { "strict": False, "debug": False, "entity_id": "https://your-idp.com/entity", "single_sign_on_service_url": "https://your-idp.com/sso", "single_sign_on_service_binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect", "single_logout_service_url": "https://your-idp.com/slo", "single_logout_service_binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect", "callback_url": "http://your-app.com/auth/saml/callback", "x509cert_path": "/path/to/certificate.pem", "x509cert": "-----BEGIN CERTIFICATE-----\n...certificate content...\n-----END CERTIFICATE-----", "cert_fingerprint": "AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01", "cert_fingerprint_algorithm": "sha256", "security": { "nameIdEncrypted": False, "authnRequestsSigned": False, "logoutRequestSigned": False, "logoutResponseSigned": False, "signMetadata": False, "wantMessagesSigned": False, "wantAssertionsSigned": False, "wantAssertionsEncrypted": False, "wantNameId": True, "wantNameIdEncrypted": False, "wantAttributeStatement": True, "requestedAuthnContext": True, "requestedAuthnContextComparison": "exact", "failOnAuthnContextMismatch": False, "metadataValidUntil": "2023-12-31T23:59:59Z", "metadataCacheDuration": "PT24H", "allowSingleLabelDomains": False, "signatureAlgorithm": "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", "digestAlgorithm": "http://www.w3.org/2001/04/xmlenc#sha256", "allowRepeatAttributeName": False, "rejectDeprecatedAlgorithm": True }, "cookie": { "max_age": 12, "expires": 12, "path": "/es", "domain": "", "secure": False, "httponly": False, "samesite": "lax" }, "attributesMapping": { "id": "userID", "account": "email", "roles": ["role1", "role2"] } }
OIDC (OpenID Connect) authentication is an authentication protocol built on top of the OAuth 2.0 framework. It provides a standardized way for clients (relying parties) to authenticate users by leveraging an Identity Provider (IdP).Configuration
Property | Description | Default | Type | Required |
---|---|---|---|---|
client_id | A unique identifier assigned to the client application by the IdP. It identifies the client application during authentication and authorization requests. | string | Yes | |
openid_configuration_uri | URI to the OpenID Connect configuration values from the provider's Well-Known Configuration Endpoint | string | Yes | |
callback_url | The URL to which the IdP will redirect the user after successful authentication. It must match one of the registered redirect URIs for the client application. | http://localhost:8085/es/auth/oidc/callback | string | No |
scope | Defines the permissions or claims requested by the client application. It may include values like openid (required for OIDC), profile , email , offline_access , or custom scopes defined by the IdP. | ["openid", "email", "profile"] | array of strings | No |
cookie | Cookie configuration to store the JWT with the current session | CookieConfig | Yes | |
attributesMapping | Attribute Mapping, remaps any value in the user data provided by the authentication service, into the User data available throughout the server. The way it serves is for each key:value looks for the value as a key in the user data from the service, and remaps it with the key in the User data for the server. The original key is kept as well as any other non-specified value. | AttributesMapping | Yes |
'oidc': { "client_id": "your-client-id", "openid_configuration_uri": "https://your-provider.com/.well-known/openid-configuration", "callback_url": "http://localhost:8085/es/auth/oidc/callback", "scope": ["openid", "email", "profile"], "attributesMapping": { "id": "sub", "account": "email", "roles": ["role1", "role2"] } }
Delegated is a JWT validation with JWKS (JSON Web Key Set) involves verifying the authenticity and integrity of a JWT by using public keys obtained from the IdP's JWKS endpoint.By utilizing JWKS for JWT validation, the client can ensure that the token was issued by a trusted party (IdP) and has not been tampered with. The use of public keys enables cryptographic verification, as only the corresponding private key held by the IdP can produce a valid signature for the JWT.
Property | Description | Default | Type | Required |
---|---|---|---|---|
debug | Debug mode flag | false | boolean | No |
jwks_url | JWKS (JSON Web Key Set) URL is a location where public keys used for verifying JSON Web Tokens (JWTs) can be retrieved | string | No | |
audience | It specifies the entity or service for which the JWT is issued. The audience claim helps ensure that JWTs are only accepted by the intended recipients, providing an extra layer of security | string | No | |
attributesMapping | Attribute Mapping, remaps any value in the user data provided by the authentication service into the User data available throughout the server | AttributesMapping | Yes |
'delegated': { "debug": False, "jwks_url": "https://your-idp.com/.well-known/jwks.json", "audience": "your-service-audience", "attributesMapping": { "id": "sub", "account": "email", "roles": ["role1", "role2"] } }
The Encryption section of the SearchAPI project documentation provides an overview of the encryption functionalities implemented within the project. Encryption is a vital aspect of securing sensitive data, ensuring its confidentiality and integrity.
This section focuses on two essential functions: encrypt
and decrypt
. These functions are part of the utils.crypto
module and provide convenient encryption and decryption capabilities for developers working on the SearchAPI project.
Property | Description | Type | Required |
---|---|---|---|
secret_key | Piece of information or parameter that is used to encrypt and decrypt messages in a symmetric. The size of the secret key should be no less than 32 characters. If no secret key is specified, one will be created in the config/auth folder | string/file-path | Yes |
This section provides an overview of the encryption mechanisms used in the SearchAPI project to secure sensitive data during transit and at rest.
'encryption': { "secret_key": "/path/to/secret.key" }
or
'encryption': { "secret_key": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6" }
If no secret_key
is specified, a new secret key will be automatically generated and saved in the config/auth
folder.
Please note that the secret_key
property can either be a file path (string with format "file-path") or a string value. Ensure that the secret key is secure and has a sufficient length for encryption purposes.
The utils.crypto
module provides various encryption and cryptographic utility functions used within the SearchAPI project. These functions are designed to ensure the security and integrity of sensitive data. This document outlines the available functions and their usage.
hash_sha256(data: Union[str, bytes]) -> str
This function computes the SHA-256 hash of the input data and returns it as a hexadecimal code. The data
parameter can be either a string or a byte array. The returned hash value is a string.
hash_sha1(data: Union[str, bytes]) -> str
This function computes the SHA-1 hash of the input data and returns it as a hexadecimal code. The data
parameter can be either a string or a byte array. The returned hash value is a string.
generate_iv()
This function generates a random Initialization Vector (IV) of 16 bytes. The IV is used for encryption and decryption processes and ensures the uniqueness and unpredictability of encrypted data.
generate_secret_key(size: int = 32) -> str
This function generates a secret key of the specified size
(default is 32 bytes). The secret key is used for encryption and decryption. The returned key is a base64-encoded string.
is_encrypted(text: str) -> bool
This function checks whether the given text
is encrypted. It returns True
if the text has the expected encryption prefix ("encrypted:").
encrypt(text: str, iv: Union[bytes, bytearray, memoryview] = None) -> str
This function encrypts the provided text
using AES encryption. If an initialization vector (iv
) is not provided, a random IV is generated. The encrypted text is returned with the prefix "encrypted:" and includes the IV and ciphertext.
decrypt(text: str) -> str
This function decrypts the given text
using AES decryption. If the text is not encrypted (does not have the encryption prefix), it returns the original text. Otherwise, it extracts the IV and ciphertext from the encrypted text and performs decryption to obtain the original plaintext.
To use the functions from utils.crypto
, you can import them as follows:
from utils.crypto import hash_sha256, hash_sha1, generate_iv, generate_secret_key, is_encrypted, encrypt, decrypt
You can then call the functions according to your requirements. For example:
data = "Hello, World!" # Compute SHA256 hash hash_value = hash_sha256(data) print(f"SHA256 hash: {hash_value}") # Generate a random IV iv = generate_iv() print(f"Generated IV: {iv}") # Generate a secret key secret_key = generate_secret_key() print(f"Generated secret key: {secret_key}") # Check if a text is encrypted encrypted_text = encrypt(data) is_text_encrypted = is_encrypted(encrypted_text) print(f"Is the text encrypted? {is_text_encrypted}") # Decrypt the encrypted text decrypted_text = decrypt(encrypted_text) print(f"Decrypted text: {decrypted_text}")
By utilizing the functions provided in utils.crypto
, you can enhance the security and encryption capabilities within the SearchAPI project.