Module:Sensitive IP addresses/API: Difference between revisions

Content deleted Content added
test getRanges to show IP ranges equivalent to collection
add SensitiveEntity class; this is meant to be used for matching IPs and subnets with entity data
Line 10:
}
 
-------------------------------------------------------------------------------
-- Plan of attack:
-- SensitiveEntity class
-- * Load the data from Module:Sensitive IP addresses/list via a formatting module
-- A country or organization for which blocks must be handled with care.
-- at Module:Sensitive IP addresses/data
-- Media organizations may inspect block messages for IP addresses and ranges
-- * This module will do preprocessing that must be done for every query
-- belonging to these entities and those messages may end up in the press.
-- * Make an API so that other modules can query this module for data about
-------------------------------------------------------------------------------
-- sensitive IPs and ranges.
 
-- * Export query results as both a Lua table and as JSON
local SensitiveEntity = {}
-- * Use this API to create a table to be used in
SensitiveEntity.__index = SensitiveEntity
-- [[Template:Sensitive IP addresses]].
 
do
-- Private methods
local function addRanges(self, key, collectionConstructor, ranges)
if ranges and #ranges > 0 then
self[key] = collectionConstructor()
for i, range in ipairs(ranges) do
self[key]:addSubnet(Subnet.new(range))
end
end
end
 
-- Constructor
function SensitiveEntity.new(data)
local self = setmetatable({}, SensitiveEntity)
 
-- Set data
self.data = data
addRanges(self, 'v4Collection', IPv4Collection.new, data.ipv4Ranges)
addRanges(self, 'v6Collection', IPv6Collection.new, data.ipv6Ranges)
 
return self
end
end
 
function SensitiveEntity:getDataItem(key)
return self.data[key]
end
 
function SensitiveEntity:matchesIPOrRange(str)
checkType('matchesIPOrRange', 1, str, 'string')
 
-- Get the IPAddress or Subnet object for str
local isIP, isSubnet, obj
isIP, obj = pcall(IPAddress.new, str)
if isIP and not ip then
isIP = false
end
if not isIP then
isSubnet, obj = pcall(Subnet.new, str)
if not isSubnet or not subnet then
error(string.format(
"'%s' is not a valid IP address or CIDR string",
str
), 2)
end
end
 
-- Try matching the object to the appropriate collection
local function isInCollection(collection, obj, isIP)
if isIP then
return collection and collection:containsIP(obj) or false
else
return collection and collection:overlapsSubnet(obj) or false
end
end
 
if obj:isIPv4() then
return isInCollection(self.v4Collection, obj, isIP)
else
return isInCollection(self.v6Collection, obj, isIP)
end
end
 
-------------------------------------------------------------------------------