srctree

Gregory Mullen parent b95ddfe0 4aaa87e2
add malicious bot detection & expose bot results

inlinesplit
src/bot-detection.zig added: 28, removed: 8, total 20
@@ -25,8 +25,7 @@ pub const ANOMALY_MAX: f16 = 0.5;
pub const BOT_DEVIANCE: f16 = 0.2;
 
pub fn init(r: *const Request) BotDetection {
if (r.user_agent == null) return .default_malicious;
const ua = r.user_agent.?;
const ua: UA = r.user_agent orelse return .default_malicious;
 
var bot: BotDetection = .default;
 
 
src/bot-detection/bots.zig added: 28, removed: 8, total 20
@@ -40,6 +40,7 @@ pub const Identity = struct {
 
pub const Bots = enum {
googlebot,
malicious,
unknown,
 
pub const fields = @typeInfo(Bots).@"enum".fields;
@@ -58,6 +59,7 @@ pub const bots: std.EnumArray(Bots, Identity) = .{
},
},
},
.{ .bot = .malicious, .network = null },
.{ .bot = .unknown, .network = null },
},
};
 
src/user-agent.zig added: 28, removed: 8, total 20
@@ -5,13 +5,16 @@
//! TODO write doc comments
string: []const u8,
resolved: Resolved,
bot_validation: if (BOTDETC_ENABLED) ?BotDetection else ?void = null,
 
const UserAgent = @This();
 
pub const BotDetection = @import("bot-detection.zig");
 
pub fn botDetectionDump(ua: UserAgent, r: *const Request) void {
if (comptime !BOTDETC_ENABLED) @compileError("Bot Detection is currently disabled");
 
const bd: BotDetection = .init(r);
const bd: BotDetection = ua.bot_validation orelse .init(r);
//std.debug.print("ua detection: {s} \n", .{ua.string});
std.debug.print("ua detection: {} \n", .{ua.resolved});
std.debug.print("bot detection: {} \n", .{bd});
@@ -27,6 +30,10 @@ pub const Resolved = union(enum) {
script: Script,
unknown: Other,
 
pub const malicious: Resolved = .{
.bot = .malicious,
};
 
pub fn init(str: []const u8) Resolved {
if (startsWith(u8, str, "Mozilla/")) {
return .mozilla(str);
@@ -188,6 +195,7 @@ pub const Bot = struct {
pub const Bots = BotDetection.bots.Bots;
 
pub const unknown: Bot = .{ .name = .unknown };
pub const malicious: Bot = .{ .name = .malicious };
};
 
pub const Browser = struct {
@@ -237,11 +245,20 @@ pub fn init(ua_str: []const u8) UserAgent {
return .{
.string = ua_str,
.resolved = .init(ua_str),
.bot_validation = null,
};
}
 
const Request = @import("request.zig");
pub const BotDetection = @import("bot-detection.zig");
pub fn validate(ua: *UserAgent, r: *const Request) !bool {
if (!BOTDETC_ENABLED) @compileError("Bot Detection is currently disabled");
ua.bot_validation = .init(r);
 
if (ua.bot_validation.?.malicious) {
ua.resolved = .malicious;
return false;
}
return true;
}
 
const BOTDETC_ENABLED: bool = verse_buildopts.botdetection or builtin.is_test;
 
@@ -250,6 +267,8 @@ test UserAgent {
_ = &BotDetection;
}
 
const Request = @import("request.zig");
 
const std = @import("std");
const log = std.log.scoped(.botdetection);
const builtin = @import("builtin");