// SPDX-FileCopyrightText: 2024 Redict Contributors
// SPDX-FileCopyrightText: 2024 Salvatore Sanfilippo <antirez at gmail dot com>
//
// SPDX-License-Identifier: BSD-3-Clause
// SPDX-License-Identifier: LGPL-3.0-only

/* define macros for having usleep */
#define _BSD_SOURCE
#define _DEFAULT_SOURCE

#include "redictmodule.h"

#include <string.h>
#include <unistd.h>
#include <pthread.h>

#define UNUSED(V) ((void) V)

// A simple global user
static RedictModuleUser *global = NULL;
static long long client_change_delta = 0;

void UserChangedCallback(uint64_t client_id, void *privdata) {
    REDICTMODULE_NOT_USED(privdata);
    REDICTMODULE_NOT_USED(client_id);
    client_change_delta++;
}

int Auth_CreateModuleUser(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    if (global) {
        RedictModule_FreeModuleUser(global);
    }

    global = RedictModule_CreateModuleUser("global");
    RedictModule_SetModuleUserACL(global, "allcommands");
    RedictModule_SetModuleUserACL(global, "allkeys");
    RedictModule_SetModuleUserACL(global, "on");

    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

int Auth_AuthModuleUser(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    uint64_t client_id;
    RedictModule_AuthenticateClientWithUser(ctx, global, UserChangedCallback, NULL, &client_id);

    return RedictModule_ReplyWithLongLong(ctx, (uint64_t) client_id);
}

int Auth_AuthRealUser(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 2) return RedictModule_WrongArity(ctx);

    size_t length;
    uint64_t client_id;

    RedictModuleString *user_string = argv[1];
    const char *name = RedictModule_StringPtrLen(user_string, &length);

    if (RedictModule_AuthenticateClientWithACLUser(ctx, name, length,
            UserChangedCallback, NULL, &client_id) == REDICTMODULE_ERR) {
        return RedictModule_ReplyWithError(ctx, "Invalid user");
    }

    return RedictModule_ReplyWithLongLong(ctx, (uint64_t) client_id);
}

/* This command redacts every other arguments and returns OK */
int Auth_RedactedAPI(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    for(int i = argc - 1; i > 0; i -= 2) {
        int result = RedictModule_RedactClientCommandArgument(ctx, i);
        RedictModule_Assert(result == REDICTMODULE_OK);
    }
    return RedictModule_ReplyWithSimpleString(ctx, "OK");
}

int Auth_ChangeCount(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    long long result = client_change_delta;
    client_change_delta = 0;
    return RedictModule_ReplyWithLongLong(ctx, result);
}

/* The Module functionality below validates that module authentication callbacks can be registered
 * to support both non-blocking and blocking module based authentication. */

/* Non Blocking Module Auth callback / implementation. */
int auth_cb(RedictModuleCtx *ctx, RedictModuleString *username, RedictModuleString *password, RedictModuleString **err) {
    const char *user = RedictModule_StringPtrLen(username, NULL);
    const char *pwd = RedictModule_StringPtrLen(password, NULL);
    if (!strcmp(user,"foo") && !strcmp(pwd,"allow")) {
        RedictModule_AuthenticateClientWithACLUser(ctx, "foo", 3, NULL, NULL, NULL);
        return REDICTMODULE_AUTH_HANDLED;
    }
    else if (!strcmp(user,"foo") && !strcmp(pwd,"deny")) {
        RedictModuleString *log = RedictModule_CreateString(ctx, "Module Auth", 11);
        RedictModule_ACLAddLogEntryByUserName(ctx, username, log, REDICTMODULE_ACL_LOG_AUTH);
        RedictModule_FreeString(ctx, log);
        const char *err_msg = "Auth denied by Misc Module.";
        *err = RedictModule_CreateString(ctx, err_msg, strlen(err_msg));
        return REDICTMODULE_AUTH_HANDLED;
    }
    return REDICTMODULE_AUTH_NOT_HANDLED;
}

int test_rm_register_auth_cb(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    RedictModule_RegisterAuthCallback(ctx, auth_cb);
    RedictModule_ReplyWithSimpleString(ctx, "OK");
    return REDICTMODULE_OK;
}

/*
 * The thread entry point that actually executes the blocking part of the AUTH command.
 * This function sleeps for 0.5 seconds and then unblocks the client which will later call
 * `AuthBlock_Reply`.
 * `arg` is expected to contain the RedictModuleBlockedClient, username, and password.
 */
void *AuthBlock_ThreadMain(void *arg) {
    usleep(500000);
    void **targ = arg;
    RedictModuleBlockedClient *bc = targ[0];
    int result = 2;
    const char *user = RedictModule_StringPtrLen(targ[1], NULL);
    const char *pwd = RedictModule_StringPtrLen(targ[2], NULL);
    if (!strcmp(user,"foo") && !strcmp(pwd,"block_allow")) {
        result = 1;
    }
    else if (!strcmp(user,"foo") && !strcmp(pwd,"block_deny")) {
        result = 0;
    }
    else if (!strcmp(user,"foo") && !strcmp(pwd,"block_abort")) {
        RedictModule_BlockedClientMeasureTimeEnd(bc);
        RedictModule_AbortBlock(bc);
        goto cleanup;
    }
    /* Provide the result to the blocking reply cb. */
    void **replyarg = RedictModule_Alloc(sizeof(void*));
    replyarg[0] = (void *) (uintptr_t) result;
    RedictModule_BlockedClientMeasureTimeEnd(bc);
    RedictModule_UnblockClient(bc, replyarg);
cleanup:
    /* Free the username and password and thread / arg data. */
    RedictModule_FreeString(NULL, targ[1]);
    RedictModule_FreeString(NULL, targ[2]);
    RedictModule_Free(targ);
    return NULL;
}

/*
 * Reply callback for a blocking AUTH command. This is called when the client is unblocked.
 */
int AuthBlock_Reply(RedictModuleCtx *ctx, RedictModuleString *username, RedictModuleString *password, RedictModuleString **err) {
    REDICTMODULE_NOT_USED(password);
    void **targ = RedictModule_GetBlockedClientPrivateData(ctx);
    int result = (uintptr_t) targ[0];
    size_t userlen = 0;
    const char *user = RedictModule_StringPtrLen(username, &userlen);
    /* Handle the success case by authenticating. */
    if (result == 1) {
        RedictModule_AuthenticateClientWithACLUser(ctx, user, userlen, NULL, NULL, NULL);
        return REDICTMODULE_AUTH_HANDLED;
    }
    /* Handle the Error case by denying auth */
    else if (result == 0) {
        RedictModuleString *log = RedictModule_CreateString(ctx, "Module Auth", 11);
        RedictModule_ACLAddLogEntryByUserName(ctx, username, log, REDICTMODULE_ACL_LOG_AUTH);
        RedictModule_FreeString(ctx, log);
        const char *err_msg = "Auth denied by Misc Module.";
        *err = RedictModule_CreateString(ctx, err_msg, strlen(err_msg));
        return REDICTMODULE_AUTH_HANDLED;
    }
    /* "Skip" Authentication */
    return REDICTMODULE_AUTH_NOT_HANDLED;
}

/* Private data freeing callback for Module Auth. */
void AuthBlock_FreeData(RedictModuleCtx *ctx, void *privdata) {
    REDICTMODULE_NOT_USED(ctx);
    RedictModule_Free(privdata);
}

/* Callback triggered when the engine attempts module auth
 * Return code here is one of the following: Auth succeeded, Auth denied,
 * Auth not handled, Auth blocked.
 * The Module can have auth succeed / denied here itself, but this is an example
 * of blocking module auth.
 */
int blocking_auth_cb(RedictModuleCtx *ctx, RedictModuleString *username, RedictModuleString *password, RedictModuleString **err) {
    REDICTMODULE_NOT_USED(username);
    REDICTMODULE_NOT_USED(password);
    REDICTMODULE_NOT_USED(err);
    /* Block the client from the Module. */
    RedictModuleBlockedClient *bc = RedictModule_BlockClientOnAuth(ctx, AuthBlock_Reply, AuthBlock_FreeData);
    int ctx_flags = RedictModule_GetContextFlags(ctx);
    if (ctx_flags & REDICTMODULE_CTX_FLAGS_MULTI || ctx_flags & REDICTMODULE_CTX_FLAGS_LUA) {
        /* Clean up by using RedictModule_UnblockClient since we attempted blocking the client. */
        RedictModule_UnblockClient(bc, NULL);
        return REDICTMODULE_AUTH_HANDLED;
    }
    RedictModule_BlockedClientMeasureTimeStart(bc);
    pthread_t tid;
    /* Allocate memory for information needed. */
    void **targ = RedictModule_Alloc(sizeof(void*)*3);
    targ[0] = bc;
    targ[1] = RedictModule_CreateStringFromString(NULL, username);
    targ[2] = RedictModule_CreateStringFromString(NULL, password);
    /* Create bg thread and pass the blockedclient, username and password to it. */
    if (pthread_create(&tid, NULL, AuthBlock_ThreadMain, targ) != 0) {
        RedictModule_AbortBlock(bc);
    }
    return REDICTMODULE_AUTH_HANDLED;
}

int test_rm_register_blocking_auth_cb(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    RedictModule_RegisterAuthCallback(ctx, blocking_auth_cb);
    RedictModule_ReplyWithSimpleString(ctx, "OK");
    return REDICTMODULE_OK;
}

/* This function must be present on each Redict module. It is used in order to
 * register the commands into the Redict server. */
int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    if (RedictModule_Init(ctx,"testacl",1,REDICTMODULE_APIVER_1)
        == REDICTMODULE_ERR) return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"auth.authrealuser",
        Auth_AuthRealUser,"no-auth",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"auth.createmoduleuser",
        Auth_CreateModuleUser,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"auth.authmoduleuser",
        Auth_AuthModuleUser,"no-auth",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"auth.changecount",
        Auth_ChangeCount,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"auth.redact",
        Auth_RedactedAPI,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"testmoduleone.rm_register_auth_cb",
        test_rm_register_auth_cb,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"testmoduleone.rm_register_blocking_auth_cb",
        test_rm_register_blocking_auth_cb,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    return REDICTMODULE_OK;
}

int RedictModule_OnUnload(RedictModuleCtx *ctx) {
    UNUSED(ctx);

    if (global)
        RedictModule_FreeModuleUser(global);

    return REDICTMODULE_OK;
}
